﻿#include "dynamicplot.h"

DynamicPlot::DynamicPlot(QString title,qreal *buffer,int bufferLen,double stepLen,int minX,int maxX,int minY,int maxY)
    : minX(minX)
    , maxX(maxX)
    , minY(minY)
    , maxY(maxY)
    , title(title)
    , buffer(buffer)
    , bufferLen(bufferLen)
    , stepLen(stepLen)
{
    chart = new QChart();       //创建图表实例
    series = new QLineSeries(); //创建序列实例
    chart->addSeries(series);   //让图表与序列建立联系
    chart->setTitle(title);     //设置图表标题
    chart->legend()->hide();    //关闭图例
    chart->createDefaultAxes(); //创建默认坐标轴

//    series->setName(title);     //设置图例标题

    //-----------设置x轴--------------
    chart->axes(Qt::Horizontal).back()->setTitleText("X");
    chart->axes(Qt::Horizontal).back()->setRange(minX, maxX);
//    chart->axes(Qt::Horizontal).back()->setGridLineVisible(false);
    //-----------设置Y轴--------------
    chart->axes(Qt::Vertical).back()->setTitleText("Y");
    chart->axes(Qt::Vertical).back()->setRange(minY, maxY);
//    chart->axes(Qt::Vertical).back()->setGridLineVisible(false);

    chartView = new QChartView(chart);//创建图表查看实例
}

void DynamicPlot::freshPlot()
{
    series->clear();        //清除序列中的所有元素
    for(int i=0; i < bufferLen; i++)
    {
        series->append((qreal)i*stepLen,buffer[i]);
    }
}

QChartView *DynamicPlot::getChartView()
{
    return chartView;
}

void DynamicPlot::destroy()
{
    if(chart != nullptr)
    {
        delete chart;
    }
    if(series != nullptr)
    {
        delete series;
    }
    if(chartView != nullptr)
    {
        delete chartView;
    }
}
